<template>
  <view class="order-content">
    <u-navbar bgColor="#fff" :safeAreaInsetTop="true" :placeholder="true" :height="30">
      <view slot="left"></view>
      <view slot="center" class="search-box">
        <view class="inner-i">
          <view style="height: 30rpx"></view>
          <u-search v-model="searchValue" @search="getData" placeholder="搜索作品名" bgColor="#f3f3f3" :showAction="false"></u-search>
        </view>
      </view>
    </u-navbar>
    <view class="inner">
      <Dynamic
        v-for="(item, index) in dataList"
        :key="index"
        :imgList="item.imgList"
        :redioList="item.redioList"
        :commentList="item.commentList"
        :avatar="item.avatar"
        :name="item.name"
        :publishTime="item.publishTime"
        :content="item.content"
        :isLike="item.isLike"
        :isGiveReward="item.isGiveReward"
        :likeNumber="item.likeNumber"
        :giveRewardNumber="item.giveRewardNumber"
        :chatNumber="item.chatNumber"
        :itemAll="item"
        @clickDynamic="clickDynamic(index)"
        @clickUser="clickUser(item.id)"
        @clickFocus="clickFocus(index)"
        @clickThumbsup="clickThumbsup(item)"
        @clickGiveReward="clickGiveReward(item.id)"
        @clickChat="clickChat(item)"
        @play="toNav(item)"
      ></Dynamic>
    </view>
    <u-loadmore :status="loadStatus" @loadmore="getList('more')" />
    <u-popup :show="showPopup" @close="showPopup = false">
      <view class="comment-popup">
        <u--textarea
          autoHeight
          count
          :maxlength="200"
          v-model="comments"
          placeholder="请输入内容"
        ></u--textarea>
        <view class="sub">
          <u-button text="发送" type="success" @click="sendComment"></u-button>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
    <cm-devtool />
  </view>
</template>

<script>
import Dynamic from '@/components/qizai-dynamic/Dynamic'
import headImg from '@/static/head.jpg'
import { articleList, articleComment, delArticleComment } from '@/api/yuedu'
export default {
  components: {
    Dynamic
  },
  data() {
    return {
      comments: '',
      showPopup: false,
      loadStatus: 'nomore',
      pageSize: 10,
      pageNum: 1,
      dataList: [],
      selectArticle: {},
      searchValue: null
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
    isLogin() {
      return this.$store.getters.token
    }
  },
  onLoad() {
    this.getData()
  },
  onShow() {
    // if (!this.isLogin) {
    //   setTimeout(() => {
    //     uni.navigateTo({
    //       url: '/pagesSub/userCenter/register'
    //     })
    //   }, 500)
    // }
  },
  onPullDownRefresh() {
    this.getData()
    uni.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.loadStatus !== 'nomore') {
      this.getData('more')
    }
  },
  
  onShareAppMessage() {
    return {
      // 分享卡片标题（必填，默认取小程序名称）
      title: '爱阅读·梧名',

      // 分享卡片图片（可选，需为网络图片URL，尺寸建议 300px × 300px）
      imageUrl: 'https://check-in.wuming-adv.info/top-header.jpg',

      // 分享链接路径（必填，默认打开当前页面）
      path: '/pages/rank/index',

      // 分享描述（仅在好友会话中显示，群聊不显示）
      desc: '爱阅读·会生活',

      // 自定义参数（用于接收分享来源，可选）
      success: function (res) {
        console.log('分享成功', res)
      },
      fail: function (res) {
        console.log('分享失败', res)
      }
    }
  },
  methods: {
    toNav(item) {
      if (!this.isLogin) {
        uni.navigateTo({
          url: '/pagesSub/userCenter/register'
        })
        return
      }
      uni.navigateTo({
        url: `/pagesSub/play/index?id=${item.id}`
      })
    },
    getData(type) {
      if (type == 'more') {
        this.pageNum++
      } else {
        this.pageNum = 1
        this.dataList = []
      }
      this.loadStatus = 'loading'
      const query = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        status: '0'
        // userId: this.$store.getters.userInfo.userId
      }
      if (this.searchValue) {
        query.articleTitle = this.searchValue
      }
      articleList(query).then((res) => {
        if (res.code === 200) {
          const dataList = res.rows.map((g) => {
            return {
              id: g.articleId,
              avatar: g.avatarUrl,
              name: g.userName ? g.userName : g.userId,
              publishTime: g.createTime,
              content: g.articleContent,
              articleTitle: g.articleTitle,
              articleAttaUrl: g.articleAttaUrl,
              avatarUrl: g.avatarUrl,
              // imgList: [
              //   'https://dss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1976832114,2993359804&fm=26&gp=0.jpg',
              //   'https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2369680151,826506100&fm=26&gp=0.jpg'
              // ],
              redioList: [
                {
                  name: g.articleTitle,
                  url: g.screenUrl ? g.screenUrl : g.articleAttaUrl,
                  type: g.articleType
                }
              ],
              commentList: g.comments
                ? g.comments.map((g) => {
                    return {
                      avatar: g.userName ? g.userName : g.userId,
                      msg: g.commentContent
                    }
                  })
                : [],
              isLike: !!g.upvote,
              isGiveReward: true,
              likeNumber: g.upvoteCount,
              giveRewardNumber: 2,
              chatNumber: g.commentCounts,
              isFocusOn: true
            }
          })
          this.dataList = this.dataList.concat(dataList || [])
          if (this.dataList.length >= res.total) {
            this.loadStatus = 'nomore'
          } else {
            this.loadStatus = 'loadmore'
          }
        }
      })
    },
    clickDynamic() {},
    clickUser() {},
    clickFocus() {},
    clickThumbsup(item) {
      if (!this.isLogin) {
        this.$refs.uToast.show({
          type: 'default',
          message: '请先注册！',
          duration: 2000,
          complete: () => {
            uni.navigateTo({
              url: '/pagesSub/userCenter/register'
            })
          }
        })
        return
      }
      if (!item.isLike) {
        articleComment({
          commentType: '1',
          articleId: item.id,
          userId: this.$store.getters.userInfo.userId
        }).then((res) => {
          if (res.code == 200) {
            item.isLike = !item.isLike
            if (item.likeNumber) {
              item.likeNumber += 1
            } else {
              item.likeNumber = 1
            }
          }
        })
      } else {
        delArticleComment({
          commentType: '1',
          articleId: item.id,
          userId: this.$store.getters.userInfo.userId
        }).then((res) => {
          if (res.code == 200) {
            item.isLike = !item.isLike
            item.likeNumber -= 1
          }
        })
      }
    },
    clickGiveReward() {},
    clickChat(item) {
      this.selectArticle = item
      this.comments = ''
      this.showPopup = true
    },
    clickUser() {
      // uni.navigateTo({
      //   url: '/pagesSub/detail/self'
      // })
    },
    sendComment() {
      if (!this.isLogin) {
        this.$refs.uToast.show({
          type: 'default',
          message: '请先注册！',
          duration: 2000,
          complete: () => {
            uni.navigateTo({
              url: '/pagesSub/userCenter/register'
            })
          }
        })
        return
      }
      const { id } = this.selectArticle
      articleComment({
        commentType: '2',
        articleId: id,
        commentContent: this.comments,
        userId: this.$store.getters.userInfo.userId
      }).then((res) => {
        this.$refs.uToast.show({
          type: 'default',
          message: res.msg || '操作成功',
          duration: 3000,
          complete: () => {
            if (res.code === 200) {
              this.selectArticle.commentList.push({
                avatar: this.$store.getters.userInfo.nickName,
                msg: this.comments
              })
              this.showPopup = false
              this.comments = ''
            }
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.order-content {
  padding: 20rpx;
  padding-bottom: 0;
  padding-top: 60rpx;
  .search-box {
    padding: 20rpx;
    background-color: #fff;
    width: 100%;
    .inner-i {
      padding-right: 30%;
    }
  }
}
.comment-popup {
  display: flex;
  align-items: center;
  padding: 20rpx;
  .sub {
    margin-left: 20rpx;
  }
}
</style>
